using McpApi.Models;

namespace McpApi.Services
{
    /// <summary>
    /// 工具初始化服务 - 注册所有MES工具
    /// </summary>
    public class ToolInitializationService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<ToolInitializationService> _logger;

        public ToolInitializationService(IServiceProvider serviceProvider, ILogger<ToolInitializationService> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("开始初始化MCP工具...");

            using var scope = _serviceProvider.CreateScope();
            var toolRegistry = scope.ServiceProvider.GetRequiredService<IToolRegistry>();
            var mesToolService = scope.ServiceProvider.GetRequiredService<MESToolService>();
            var weatherService = scope.ServiceProvider.GetRequiredService<WeatherService>();
            var weatherAnalysisService = scope.ServiceProvider.GetRequiredService<WeatherImpactAnalysisService>();

            // 注册MES工具
            await RegisterProductionOrderTool(toolRegistry, mesToolService);
            await RegisterInventoryTool(toolRegistry, mesToolService);
            await RegisterBOMTool(toolRegistry, mesToolService);
            await RegisterReportTool(toolRegistry, mesToolService);

            // 注册天气工具
            await RegisterWeatherTools(toolRegistry, weatherService, weatherAnalysisService);

            _logger.LogInformation("MCP工具初始化完成，共注册 {Count} 个工具", toolRegistry.GetToolCount());
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("工具初始化服务停止");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 注册生产订单查询工具
        /// </summary>
        private async Task RegisterProductionOrderTool(IToolRegistry toolRegistry, MESToolService mesToolService)
        {
            var tool = new Tool
            {
                Name = "query_production_orders",
                Description = "查询生产订单信息，支持按订单号、状态等条件筛选。可以获取订单的详细信息包括进度、产品信息、计划时间等。",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["orderId"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "生产订单编号，如PO20241201001"
                        },
                        ["status"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "订单状态",
                            Enum = new List<string> { "待开始", "进行中", "已完成", "已暂停" }
                        },
                        ["pageSize"] = new PropertySchema
                        {
                            Type = "integer",
                            Description = "每页记录数，默认10"
                        },
                        ["pageIndex"] = new PropertySchema
                        {
                            Type = "integer",
                            Description = "页码，从1开始，默认1"
                        }
                    },
                    Required = new List<string>()
                }
            };

            await toolRegistry.RegisterToolAsync(tool, mesToolService.QueryProductionOrdersAsync);
        }

        /// <summary>
        /// 注册物料库存查询工具
        /// </summary>
        private async Task RegisterInventoryTool(IToolRegistry toolRegistry, MESToolService mesToolService)
        {
            var tool = new Tool
            {
                Name = "query_material_inventory",
                Description = "查询物料库存信息，可以按物料编码、名称、仓库等条件查询当前库存、可用库存、预留库存等信息。",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["materialCode"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "物料编码，如MAT001"
                        },
                        ["materialName"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "物料名称，支持模糊查询"
                        },
                        ["warehouseCode"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "仓库编码，如WH01"
                        }
                    },
                    Required = new List<string>()
                }
            };

            await toolRegistry.RegisterToolAsync(tool, mesToolService.QueryMaterialInventoryAsync);
        }

        /// <summary>
        /// 注册BOM查询工具
        /// </summary>
        private async Task RegisterBOMTool(IToolRegistry toolRegistry, MESToolService mesToolService)
        {
            var tool = new Tool
            {
                Name = "query_bom_info",
                Description = "查询产品的物料清单(BOM)信息，包括产品结构、物料组成、用量等详细信息。",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["productCode"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "产品编码，如PROD001"
                        },
                        ["version"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "BOM版本号，默认为最新版本"
                        }
                    },
                    Required = new List<string> { "productCode" }
                }
            };

            await toolRegistry.RegisterToolAsync(tool, mesToolService.QueryBOMInfoAsync);
        }

        /// <summary>
        /// 注册生产报表工具
        /// </summary>
        private async Task RegisterReportTool(IToolRegistry toolRegistry, MESToolService mesToolService)
        {
            var tool = new Tool
            {
                Name = "generate_production_report",
                Description = "生成生产报表，包括日报、周报、月报等，提供生产统计数据、效率分析、订单完成情况等信息。",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["reportType"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "报表类型",
                            Enum = new List<string> { "daily", "weekly", "monthly" }
                        },
                        ["startDate"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "开始日期，格式：YYYY-MM-DD"
                        },
                        ["endDate"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "结束日期，格式：YYYY-MM-DD"
                        }
                    },
                    Required = new List<string> { "reportType" }
                }
            };

            await toolRegistry.RegisterToolAsync(tool, mesToolService.GenerateProductionReportAsync);
        }

        /// <summary>
        /// 注册天气相关工具
        /// </summary>
        private async Task RegisterWeatherTools(IToolRegistry toolRegistry, WeatherService weatherService, WeatherImpactAnalysisService analysisService)
        {
            // 当前天气查询工具
            var currentWeatherTool = new Tool
            {
                Name = "get_current_weather",
                Description = "获取指定城市的当前天气信息，包括温度、湿度、风速、天气状况等",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["city"] = new PropertySchema { Type = "string", Description = "城市名称，默认为北京" },
                        ["countryCode"] = new PropertySchema { Type = "string", Description = "国家代码，默认为CN" }
                    },
                    Required = new List<string>()
                }
            };
            await toolRegistry.RegisterToolAsync(currentWeatherTool, weatherService.GetCurrentWeatherAsync);

            // 天气预报工具
            var forecastTool = new Tool
            {
                Name = "get_weather_forecast",
                Description = "获取指定城市的天气预报，支持1-5天的预报信息",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["city"] = new PropertySchema { Type = "string", Description = "城市名称，默认为北京" },
                        ["countryCode"] = new PropertySchema { Type = "string", Description = "国家代码，默认为CN" },
                        ["days"] = new PropertySchema { Type = "string", Description = "预报天数，1-5天，默认为5天" }
                    },
                    Required = new List<string>()
                }
            };
            await toolRegistry.RegisterToolAsync(forecastTool, weatherService.GetWeatherForecastAsync);

            // 天气预警检查工具
            var alertsTool = new Tool
            {
                Name = "check_weather_alerts",
                Description = "检查指定城市的天气预警信息，识别可能影响生产的恶劣天气",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["city"] = new PropertySchema { Type = "string", Description = "城市名称，默认为北京" },
                        ["countryCode"] = new PropertySchema { Type = "string", Description = "国家代码，默认为CN" }
                    },
                    Required = new List<string>()
                }
            };
            await toolRegistry.RegisterToolAsync(alertsTool, weatherService.CheckWeatherAlertsAsync);

            // 天气影响分析工具
            var impactAnalysisTool = new Tool
            {
                Name = "analyze_weather_impact",
                Description = "分析天气对MES系统的影响，提供风险评估和应对建议",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["city"] = new PropertySchema { Type = "string", Description = "城市名称，默认为北京" },
                        ["analysisType"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "分析类型：comprehensive(综合分析)、production(生产影响)、safety(安全影响)",
                            Enum = new List<string> { "comprehensive", "production", "safety", "equipment", "logistics" }
                        }
                    },
                    Required = new List<string>()
                }
            };
            await toolRegistry.RegisterToolAsync(impactAnalysisTool, analysisService.AnalyzeWeatherImpactAsync);

            // 天气预警报告工具
            var alertReportTool = new Tool
            {
                Name = "generate_weather_alert_report",
                Description = "生成详细的天气预警报告，包含影响评估和应对措施",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["city"] = new PropertySchema { Type = "string", Description = "城市名称，默认为北京" },
                        ["severity"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "预警严重程度过滤：all(全部)、low(低级)、medium(中级)、high(高级)、critical(严重)",
                            Enum = new List<string> { "all", "low", "medium", "high", "critical" }
                        }
                    },
                    Required = new List<string>()
                }
            };
            await toolRegistry.RegisterToolAsync(alertReportTool, analysisService.GenerateWeatherAlertReportAsync);

            // 天气适应性建议工具
            var adaptationAdviceTool = new Tool
            {
                Name = "get_weather_adaptation_advice",
                Description = "根据天气预报提供生产适应性建议和调整方案",
                InputSchema = new ToolInputSchema
                {
                    Type = "object",
                    Properties = new Dictionary<string, PropertySchema>
                    {
                        ["city"] = new PropertySchema { Type = "string", Description = "城市名称，默认为北京" },
                        ["timeHorizon"] = new PropertySchema
                        {
                            Type = "string",
                            Description = "时间范围：24h(24小时)、48h(48小时)、72h(72小时)、week(一周)",
                            Enum = new List<string> { "24h", "48h", "72h", "week" }
                        }
                    },
                    Required = new List<string>()
                }
            };
            await toolRegistry.RegisterToolAsync(adaptationAdviceTool, analysisService.GetWeatherAdaptationAdviceAsync);
        }
    }
}
